using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using AdminApi.Authorize;
using AdminApi.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

namespace AdminApi;

[Route("api/[controller]/[action]")]
[ApiController]
public class TestController : ControllerBase
{
    private CustomJWTService _jwtService;

    public TestController(CustomJWTService jwtService)
    {
        _jwtService = jwtService;
    }

    [HttpPost]
    public string GetToken(UserRes userRes)
    {
        return _jwtService.GetToken(userRes);
    }

    [HttpGet]
    [Authorize]
    [AdminAuthorize(AuthorizeRoleName.Administrator)]
    public UserRes GetUser()
    {
        var userName = User.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Name)?.Value;
        //解析token
        string token = Request.Headers["Authorization"];
        if (token.StartsWith("Bearer "))
        {
            token = token.Substring("Bearer ".Length);
        }

        var handler = new JwtSecurityTokenHandler();
        var jwtToken = handler.ReadJwtToken(token);
        var nameClaim = jwtToken.Claims.FirstOrDefault(claim => claim.Type == "Name").Value;
        var passwordClaim = jwtToken.Claims.FirstOrDefault(claim => claim.Type == "Password").Value;
        var userRes = new UserRes()
        {
            Name = nameClaim,
            Password = passwordClaim
        };
         return userRes;
    }
}